package com.alibaba.citrus.cr.platform.enhance.facade.service;

import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.crplatformenhance.sso.dto.GetSSOTokenRequest;
import com.epoch.app.crplatformenhance.sso.service.SSOService;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import smartbi.sdk.ClientConnector;
import smartbi.sdk.InvokeResult;

/**
 * https://wiki.smartbi.com.cn/pages/viewpage.action?pageId=51942669
 */
@Component
@Primary
public class SSOServiceImpl implements SSOService {

    Log log = Log.getLogger(SSOServiceImpl.class);

    @Override
    public Result<String> getSSOToken(GetSSOTokenRequest getSSOTokenRequest) {
        if (getSSOTokenRequest.getSsoType() == 0) {
            return smartBiSSO(getSSOTokenRequest);
        }

        return Result.success("200", "暂不支持此类型的单点登录");
    }

    @NotNull
    private Result<String> smartBiSSO(GetSSOTokenRequest getSSOTokenRequest) {
        Object token = null;
        ClientConnector conn = null;
        try {
            String domain = getSSOTokenRequest.getDomain();
            conn = new ClientConnector("https://" + domain + "/smartbi");

            // 必须以拥有系统管理员角色的用户登录，其他用户登录调用接口获取的token是null
            String admin = getSSOTokenRequest.getAdmin();
            String passwd = getSSOTokenRequest.getPasswd();
            String loginUser = getSSOTokenRequest.getLoginUser();

            boolean open = conn.open(admin, passwd);
            if (!open) {
                log.error("单点登录失败, 管理员登录失败， admin:{}", admin);
                return Result.fail("500", "单点登录失败");
            }

            // 用户名
            InvokeResult result = conn.remoteInvoke("LoginTokenModule", "generateLoginToken", new Object[]{loginUser});
            if (result == null || result.getResult() == null) {
                log.error("单点登录失败, 获取用户token失败， admin:{}, loginUser:{}, result:{}", admin, loginUser, JSON.toJSONString(result));
                return Result.fail("500", "单点登录失败");
            }

            //result.getResult()就是demo用户的token
            token = result.getResult();

            String indexUrl = "user=" + loginUser + "&password=" + token;
            log.info(indexUrl);

            return Result.success(indexUrl);
        } catch (Exception e) {
            log.error(e, "单点登录失败, getSSOTokenRequest:{}", getSSOTokenRequest);
        } finally {
            if (conn != null) {
                conn.close();
            }
        }

        return Result.fail("500", "单点登录失败");
    }
}
